package xhwl.android.pay.common;


import android.app.Activity;
import android.util.Log;

import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import xhwl.android.pay.bean.WXPayBean;
import xhwl.android.pay.utils.MD5;


/**
 * @author admin
 *
 */
public class WxpayMgr {
    private static final String TAG = "WxpayMgr";
	Activity ctx;
    PayReq req;
    IWXAPI msgApi =null;
    StringBuffer sb;
    WXPayBean bean;
    public WxpayMgr(Activity ctx, WXPayBean bean){
        this.ctx=ctx;
        msgApi = WXAPIFactory.createWXAPI(ctx, null);
        req = new PayReq();
		sb=new StringBuffer();
		msgApi.registerApp(Constants.APP_ID);
		this.bean=bean;
    }
    public void pay()
    {
    	genPayReq();
		sendPayReq();
    }

	private String genAppSign(List<NameValuePair> params) {
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < params.size(); i++) {
			sb.append(params.get(i).getName());
			sb.append('=');
			sb.append(params.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(Constants.API_KEY);

        this.sb.append("sign str\n"+sb.toString()+"\n\n");
		String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		Log.e("orion",appSign);
		return appSign;
	}

	private String genNonceStr() {
		Random random = new Random();
		return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
	}
	
	private long genTimeStamp() {
		return System.currentTimeMillis() / 1000;
	}


	private void genPayReq() {
		req.appId = Constants.APP_ID;
		req.partnerId = Constants.MCH_ID;
		req.prepayId = bean.prepay_id;
		req.packageValue = "Sign=WXPay";
		req.nonceStr = bean.nonce_str;
		req.timeStamp = String.valueOf(genTimeStamp());


		List<NameValuePair> signParams = new LinkedList<NameValuePair>();
		signParams.add(new BasicNameValuePair("appid", req.appId));
		signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
		signParams.add(new BasicNameValuePair("package", req.packageValue));
		signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
		signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
		signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

		req.sign = genAppSign(signParams);

		sb.append("sign\n"+req.sign+"\n\n");


		Log.e("orion", signParams.toString());

	}
	private void sendPayReq() {
		msgApi.registerApp(Constants.APP_ID);
		msgApi.sendReq(req);
	}


}
